<template>
	<view class="page">
		<uv-navbar :title="`${forms.id ? '编辑' : '新建'}维保工单`" placeholder bg-color="#fff" auto-back
			left-icon-color="#757575" title-style="color: #000000; font-size: 32rpx" />
		<uv-gap height="20rpx" bgColor="#F2F2F2" />
		<uv-form labelPosition="left" :model="forms" :rules="rules" ref="formRef" labelWidth="100">
			<uv-form-item label="关联项目" borderBottom required prop="projectId">
				<g-select
					v-model:value="forms.projectId"
					:list="itemList"
					key-value="id"
					key-name="name"
					align="right"
					border="none"
					title="选择项目"
					style="width: 100%;"
					placeholder="请选择项目"
					@change="changeItem"
				/>
			</uv-form-item>
			<view class="tips-box" v-if="tipsList.length > 0">
				<uv-text text="问题楼层提示：" color="#4EA770" size="28rpx" />
				<uv-text v-for="(i, k) in tipsList" :key="k" :text="
            k + 1 + ' ' + i.floorDescribe + ' ' + i.deviceName + ' ' + i.deviceItemName
          " :color="
            !forms.systemId ||
            (forms.systemId == i.systemId && !forms.inspectRecordIdList.includes(i.inspectRecordId))
              ? '#4EA770'
              : '#bdbdbd'
          " size="28rpx" margin="10rpx 0 0 0" @click="chooseCheck(i)">
				</uv-text>
			</view>
			<uv-gap height="20rpx" bgColor="#F2F2F2" />
			<uv-form-item label="系统" borderBottom required @click="showSystem" prop="systemName">
				<uv-input v-model="forms.systemName" placeholder="点击选择" disabled border="none" input-align="right"
					disabled-color="#ffffff" suffix-icon="arrow-right" suffix-icon-style="color: #BDBDBD" />
			</uv-form-item>
			<uv-form-item label="设备" :borderBottom="forms.deviceName.length == 0" required prop="deviceName">
				<uv-text suffix-icon="arrow-right" :icon-style="{
            color: '#bdbdbd',
          }" color="#bdbdbd" text="点击选择" size="14px" align="right" margin="0 4rpx 0 0"
					customStyle="padding-right: 8rpx" @click="showDevice" />
			</uv-form-item>
			<view class="position-box" v-if="forms.deviceName.length">
				<view class="position-item" v-for="(device, k) in forms.deviceName" :key="k">
					<text> {{ device }} </text>
					<uv-icon name="close-circle-fill" size="32rpx" color="#FF3B30" @click="removeDevice(k)" />
				</view>
			</view>
			<uv-form-item label="位置信息" :borderBottom="forms.positionName.length == 0" required prop="positionName">
				<uv-text suffix-icon="arrow-right" :icon-style="{
            color: '#bdbdbd',
          }" color="#bdbdbd" text="点击选择" size="14px" align="right" margin="0 4rpx 0 0"
					customStyle="padding-right: 8rpx" @click="showFloor" />
			</uv-form-item>
			<view class="position-box" v-if="forms.positionName.length">
				<view class="position-item" v-for="(floor, k) in forms.positionName" :key="k">
					<text> {{ floorInfo(floor, k) }} </text>
					<uv-icon name="close-circle-fill" size="32rpx" color="#FF3B30" @click="removePosition(k)" />
				</view>
			</view>
			<uv-form-item label="工单标题" borderBottom required prop="title">
				<uv-input v-model="forms.title" placeholder="点击填写" maxlength="30" border="none" input-align="right" />
			</uv-form-item>
			<uv-form-item label="故障内容" label-position="top" borderBottom required prop="content">
				<uv-textarea v-model="forms.content" placeholder="请输入故障内容" maxlength="500" border="none" />
			</uv-form-item>
			<uv-form-item label="位置描述" borderBottom required prop="locationDescription">
				<uv-input v-model="forms.locationDescription" maxlength="500" border="none" placeholder="点击填写" />
			</uv-form-item>
			<uv-form-item label="工单类别" borderBottom required prop="type">
				<uv-radio-group v-model="forms.type">
					<uv-radio active-color="#4ea770" :custom-style="{margin: '8px'}" label="加急工单" :name="1" />
					<uv-radio active-color="#4ea770" :custom-style="{margin: '8px'}" label="普通工单" :name="2" />
				</uv-radio-group>
			</uv-form-item>
			<uv-form-item label="备注" borderBottom required prop="remark">
				<uv-input v-model="forms.remark" maxlength="500" border="none" placeholder="点击填写" />
			</uv-form-item>
			<uv-form-item label="上传附件" prop="annexUrl">
				<uv-text suffix-icon="arrow-right" :icon-style="{
            color: '#bdbdbd',
          }" color="#bdbdbd" text="选择附件" size="14px" align="right" margin="0 4rpx 0 0"
					customStyle="padding-right: 8rpx" @click="onChangeAvatar" />
			</uv-form-item>
			<view class="image-box" v-if="forms.annexUrl.length">
				<view v-for="(url, k) in forms.annexUrl" :key="k" class="image-item">
					<view class="image-del" @click="deletePic(k)">
						<uv-icon name="close" color="#fff" />
					</view>
					<image :src="webSrc(url)" mode="aspectFill" @click="previewImage(k)" />
				</view>
			</view>
		</uv-form>
		<view class="btn-box">
			<uv-button
					text="提交"
					type="primary"
					shape="circle"
					color="#4EA770"
					:custom-style="{width: '100%'}"
					@click="handleSubmit"
				/>
		</view>
		<uv-picker ref="systemRef" :columns="systemList" confirm-color="#757575" key-name="systemName"
			@confirm="confirmSystem" />
		<uv-popup ref="deviceRef" mode="bottom" @maskClick="closeDevice" >
		<view class="device-list">
			<view class="device-list-header">
				<view @click="closeDevice">取消</view>
				<view @click="confirmDevice">确定</view>
			</view>
			<view class="device-list-body">
				<uv-checkbox-group v-model="deviceId" shape="circle" placement="column">
					<uv-checkbox 
						:customStyle="{ margin: '16rpx 0' }" 
						v-for="(item, index) in deviceList" 
						:key="index"
						active-color="#4EA770"
						:label="item.name" 
						:name="item.id"
					/>
				</uv-checkbox-group>
			</view>
		</view>
		</uv-popup>
		<uv-popup ref="edificeRef" mode="bottom">
			<uv-vtabs chain :list="edificeList" key-name="buildingName" :current="edificeIndex"
				:bar-item-badge-style="{ right: '20px', top: '12px' }" height="900rpx" bar-width="220rpx"
				bar-bg-color="#F3F3F3" :bar-style="{
          textAlign: 'center',
        }" :bar-item-active-line-style="{
          background: '#4EA770',
          height: '32rpx',
          width: '8rpx',
          top: '50%',
          transform: 'translateY(-50%)',
        }" @change="changeEdifice">
				<uv-vtabs-item v-for="(f, k) in floorList" :key="k" :index="k">
					<view class="floor-item" @click="chooseFloor(f)">
						<text class="text">{{ f.floor }}F</text>
						<uv-icon v-if="f.checked" name="checkmark-circle-fill" color="#4EA770" size="20" />
					</view>
				</uv-vtabs-item>
			</uv-vtabs>
		</uv-popup>
	</view>
</template>
<script setup>
	import {
		reactive,
		computed,
		watch,
		ref,
	} from "vue";
	import {
		onLoad,
		onBackPress
	} from "@dcloudio/uni-app";
	import {
		addOrder,
		editOrder,
		projectList,
		getOrderDetail,
		orderNoPassList,
		orderSystemList,
		orderDeviceList,
		orderEdificeList,
	} from "@/request/order.js";
	import {
		commonUpload
	} from "@/request/common.js";
	import { webSrc } from "@/common/mothed.js";

	const itemList = ref([]); // 项目列表
	const tipsList = ref([]); // 检查不合格楼层提示
	const systemRef = ref(); // 系统弹窗ref
	const systemList = ref([
		[]
	]); // 系统列表
	const deviceRef = ref(); // 设备弹窗ref
	const deviceList = ref([]); // 设备列表
	const edificeRef = ref(); // 地点弹窗ref
	const edificeList = ref([]); // 地点列表
	const edificeIndex = ref(0); // 地点索引
	const deviceId = ref([]); // 设备id
	const formRef = ref(); // 表单ref
	const forms = reactive({
		id: null, // 工单id
		projectId: "", // 项目id
		systemId: "", // 系统id
		systemName: "", // 系统名称
		deviceId: [], // 设备id
		deviceName: [], // 设备名称
		floorId: [], // 楼层ID
		positionName: [], // 位置名称
		title: "", // 工单标题
		content: "", // 故障内容
		status: 10, // 工单状态 业主固定为2
		remark: "", // 备注
		locationDescription: '', //位置描述
		type: 2, // 工单类别
		annexUrl: [], // 附件
		inspectRecordIdList: [] //区分对应的id
	});
	const rules = ref({
		projectId: [{
			required: true,
			message: "请选择项目",
			type: 'number',
			trigger: ["blur", "change"]
		}],
		systemName: [{
			required: true,
			message: "请选择系统",
			trigger: ["blur", "change"]
		}],
		deviceName: [{
			required: true,
			message: "请选择设备",
			type: "array",
			trigger: ["blur", "change"]
		}],
		positionName: [{
			required: true,
			message: "请选择位置信息",
			type: "array",
			trigger: ["blur", "change"],
		}, ],
		title: [{
			required: true,
			message: "请输入工单标题",
			trigger: ["blur", "change"]
		}],
		content: [{
			required: true,
			message: "请输入故障内容",
			trigger: ["blur", "change"]
		}],
		locationDescription: [{
			required: true,
			message: "请输入位置描述",
			trigger: ["blur", "change"]
		}],
		remark: [{
			required: true,
			message: "请输入备注",
			trigger: ["blur", "change"]
		}],
		annexUrl: [{
			required: true,
			type: "array",
			message: "请上传图片",
			trigger: ["blur", "change"]
		}]
	});
	const unBack = ref(true); // 阻止放行

	// 获取楼层列表
	const floorList = computed(() => {
		const ids = forms.floorId;
		const list = edificeList.value[edificeIndex.value]?.floorList || [];
		return list?.map((i) => {
			return {
				...i,
				checked: ids.includes(i.floorId),
			};
		});
	});

	onLoad((e) => {
		getItemList();
		if (e.id) {
			forms.id = e.id;
			getData();
		}
	});

	watch(forms, () => {
		formRef.value.clearValidate();
	}, { deep: true })

	onBackPress((e) => {
		if (unBack.value) {
			uni.showModal({
				title: "退出确认",
				content: "资料尚未提交，是否取消编辑？",
				showCancel: true,
				confirmColor: "#4EA770",
				success: ({
					confirm
				}) => {
					if (confirm) {
						unBack.value = false;
						uni.navigateBack();
					}
				},
			});
		}
		return unBack.value; //阻止返回
	});

	// 新增工单
	const handleSubmit = () => {
		formRef.value
			.validate()
			.then((valid) => {
				if (valid) {
					let data = Object.assign({}, forms);
					delete data.positionName;
					data.deviceId = data.deviceId?.join(",");
					data.deviceName = data.deviceName?.join(",");
					data.floorId = data.floorId?.join(",");
					data.annexUrl = data.annexUrl?.join(",");
					data.inspectRecordIds = data.inspectRecordIdList?.join(",");
					delete data.inspectRecordIdList;
					let request = forms.id ? editOrder : addOrder;
					request(data).then((res) => {
						if (res.code == 200) {
							uni.$emit("order");
							uni.showToast({
								title: "提交成功",
								icon: "success",
								success: () => {
									unBack.value = false;
									setTimeout(() => {
										uni.navigateBack({
											delta: 1,
										});
									}, 1500);
								},
							});
						}
					});
				}
			})
			.catch(() => {});
	};

	// 获取项目列表
	const getItemList = () => {
		projectList().then((res) => {
			if (res.code == 200) {
				itemList.value = res.data;
			}
		});
	};

	// 选择项目
	const changeItem = (e) => {
		forms.systemId = "";
		forms.systemName = "";
		forms.deviceId = [];
		forms.deviceName = "";
		forms.floorId = [];
		forms.positionName = [];
		forms.content = "";
		forms.remark = "";
		forms.locationDescription = ''
		forms.annexUrl = [];
		forms.inspectRecordIdList = []
		getOrderNoPassList();
		getSystemList();
		getFloorList();
	};

	// 获取未通过检查记录
	const getOrderNoPassList = () => {
		orderNoPassList({
			projectId: forms.projectId
		}).then((res) => {
			if (res.code == 200) {
				tipsList.value = res.data;
			}
		});
	};

	// 选择检查项
	const chooseCheck = async (val) => {
		if (
			!forms.systemId ||
			(forms.systemId == val.systemId && !forms.inspectRecordIdList.includes(val.inspectRecordId))
		) {
			forms.content = forms.content ?
				forms.content + "，" + val.problemDescription :
				val.problemDescription;
			forms.remark = forms.remark ?
				forms.remark + "，" + val.remark :
				val.remark;
			forms.locationDescription = forms.locationDescription ?
				forms.locationDescription + "，" + val.locationDescription :
				val.locationDescription;
			forms.annexUrl = forms.annexUrl.length ?
				forms.annexUrl?.concat(val.imgUrl ? val.imgUrl.split(","): []) :
				val.imgUrl ? val.imgUrl.split(","): [];
			forms.systemId = val.systemId;
			forms.systemName = systemList.value[0]?.find(
				(i) => i.systemId == val.systemId
			)?.systemName;
			await getDeviceList();
			let floorName = "";  
			edificeList.value.forEach((a) => {
				a.floorList.forEach((b) => {
					if (b.floorId == val.floorId) {
						floorName = `${b.floor}`;
					}
				});
			});
			let deviceName = ''
			deviceList.value.forEach((a) => {
				if (a.id == val.deviceId) {
					deviceName = `${a.name}`;
				}
			});
			// 位置名称
			forms.positionName = forms.positionName.length ?
				forms.positionName.concat(floorName) :
				[floorName];
			// 设备名称
			forms.deviceName = forms.deviceName.length ?
				forms.deviceName.concat(deviceName) : [deviceName];
			// 设备id
			forms.deviceId = forms.deviceId.length ?
				forms.deviceId.concat(val.deviceId) : [val.deviceId];
			// 弹出框关联id
			deviceId.value = forms.deviceId.length ?
				forms.deviceId.concat(val.deviceId) : [val.deviceId];
			forms.floorId = forms.floorId.length ?
				forms.floorId.concat(val.floorId) : [val.floorId];
			// 项目唯一id
			forms.inspectRecordIdList = forms.inspectRecordIdList.length ?
				forms.inspectRecordIdList.concat(val.inspectRecordId) : [val.inspectRecordId];
		}
	};

	// 获取系统列表
	const getSystemList = () => {
		orderSystemList(forms.projectId).then((res) => {
			if (res.code == 200) {
				systemList.value[0] = res.data;
			}
		});
	};

	// 显示系统弹窗
	const showSystem = () => {
		if (!forms.projectId) {
			uni.showToast({
				title: "请先选择项目",
				icon: "none",
			});
			return;
		}
		systemRef.value.open();
	};

	// 选择系统
	const confirmSystem = (e) => {
		forms.systemId = e.value[0]?.systemId;
		forms.systemName = e.value[0]?.systemName;
		systemRef.value.close();
		forms.deviceId = [];
		deviceId.value = [];
		forms.deviceName = [];
		forms.floorId = [];
		forms.positionName = [];
		edificeIndex.value = 0;
		forms.title = "";
		forms.content = "";
		forms.remark = "";
		forms.annexUrl = [];
		getDeviceList();
	};

	// 获取系统列表
	const getDeviceList = async () => {
		const res = await orderDeviceList(forms.systemId);
		if (res.code == 200) {
			deviceList.value = res.data;
		}
	};

	// 显示设备弹窗
	const showDevice = () => {
		if (!forms.systemId) {
			uni.showToast({
				title: "请先选择系统",
				icon: "none",
			});
			return;
		}
		deviceRef.value.open();
	};

	// 选择设备
	const confirmDevice = () => {
		forms.deviceId = deviceId.value;
		forms.deviceName = deviceId.value.map(i => deviceList.value.find(a=> a.id == i)?.name);
		deviceRef.value.close();
	};

	// 关闭设备弹窗
	const closeDevice = () => {
		deviceId.value = forms.deviceId || [];
		deviceRef.value.close();
	};

	// 删除设备
	const removeDevice = (index) => {
		uni.showModal({
			title: "删除",
			content: "确定删除该设备吗?",
			showCancel: true,
			success: ({
				confirm
			}) => {
				if (confirm) {
					forms.deviceId.splice(index, 1);
					forms.deviceName.splice(index, 1);
				}
			},
		});
	};

	// 获取楼层列表
	const getFloorList = async () => {
		const res = await orderEdificeList(forms.projectId);
		if (res.code == 200) {
			edificeList.value = res.data;
		}
	};

	// 显示楼层弹窗
	const showFloor = () => {
		if (!forms.projectId) {
			uni.showToast({
				title: "请先选择项目",
				icon: "none",
			});
			return;
		}
		edificeRef.value.open();
	};

	// 选择建筑
	const changeEdifice = (index) => {
		edificeIndex.value = index;
	};

	// 选择楼层
	const chooseFloor = (i) => {
		if (i.checked) {
			forms.floorId = forms.floorId.filter((floorId) => floorId != i.floorId);
			forms.positionName = forms.positionName.filter((floor) => floor != i.floor);
		} else {
			forms.floorId.push(i.floorId);
			forms.positionName.push(i.floor);
		}
	};

	// 楼层信息
	const floorInfo = (floor, index) => {
		let floorId = forms.floorId[index];
		let info = {};
		edificeList.value.forEach((i) => {
			i?.floorList?.forEach((j) => {
				if (floorId == j.floorId) info = i;
			});
		});
		return `${info.buildingName} ${floor}层`;
	};

	// 删除位置信息
	const removePosition = (index) => {
		uni.showModal({
			title: "删除",
			content: "确定删除该楼层吗?",
			showCancel: true,
			success: ({
				confirm
			}) => {
				if (confirm) {
					forms.floorId.splice(index, 1);
					forms.positionName.splice(index, 1);
				}
			},
		});
	};

	//上传附件
	function onChangeAvatar() {
		uni.chooseImage({
			count: 9,
			sizeType: ["compressed"],
			success: (image) => {
				image.tempFilePaths.forEach((i) => {
					commonUpload(i).then((res) => {
						if (res.code == 200) {
							forms.annexUrl.push(res.fileName);
						}
					});
				});
			},
			fail: () => {
				uni.showToast({
					title: "获取权限失败",
					icon: "none",
				})
			}
		});
	}

	// 删除图片
	const deletePic = (index) => {
		uni.showModal({
			title: "提示",
			content: "确定是否删除？",
			showCancel: true,
			success: ({
				confirm
			}) => {
				if (confirm) {
					forms.annexUrl.splice(index, 1);
				}
			},
		});
	};

	// 预览图片
	const previewImage = (k) => {
		uni.previewImage({
			urls: forms.annexUrl.map((i) => webSrc(i)),
			current: k,
		});
	};

	// 获取工单详情
	const getData = () => {
		getOrderDetail(forms.id).then(async (res) => {
			if (res.code == 200) {
				forms.projectId = res.data.projectId;
				getOrderNoPassList();
				getSystemList();
				forms.systemId = res.data.systemId;
				forms.systemName = res.data.systemName;
				await getDeviceList();
				forms.deviceId = res.data.deviceId?.split(",").map((i) => Number(i));
				deviceId.value = forms.deviceId;
				forms.deviceName = res.data.deviceName?.split(",");
				await getFloorList();
				forms.floorId = res.data.floorId?.split(",").map((i) => Number(i));
				edificeList.value.forEach((a) => {
					forms.floorId.forEach((b) => {
						if (a.floorList.find((c) => c.floorId == b)) {
							forms.positionName.push(a.floorList.find((c) => c.floorId == b)
								.floor);
						}
					});
				});
				forms.title = res.data.title;
				forms.content = res.data.content;
				forms.locationDescription = res.data.locationDescription;
				forms.type = res.data.type;
				forms.remark = res.data.remark;
				forms.annexUrl = res.data.annexUrl ? res.data.annexUrl.split(",") : [];
			}
		});
	};
</script>
<style lang="scss" scoped>
	@import "@/uni.scss";
	.device-list {
		padding: 20rpx;
		&-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;
			color: #909193;
			font-size: 30rpx;
			view {
				width: 60px;
				text-align: center
			}
		}
		&-body {
			max-height: 60vh;
			min-height: 20vh;
			overflow-y: auto;
		}
	}
	.position-box {
		border-bottom: 2rpx solid rgba(214, 215, 217, 0.5);
		display: flex;
		flex-wrap: wrap;
		padding: 0 30rpx;
		box-sizing: border-box;

		.position-item {
			padding: 8rpx;
			color: #909399;
			font-size: 28rpx;
			display: flex;
			align-items: center;
			border: 2rpx solid #dedede;
			border-radius: 8rpx;
			margin: 0 20rpx 20rpx 0;

			text {
				margin-right: 10rpx;
			}
		}
	}

	.floor-item {
		height: 100rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 48rpx 0 76rpx;
		font-size: 14px;
		color: #212121;
		box-sizing: border-box;
	}

	.image-box {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 20rpx;
		width: 100%;
		margin-top: 20rpx;
		padding: 0 30rpx;
		box-sizing: border-box;

		.image-item {
			position: relative;
			height: 156rpx;
			overflow: hidden;
			border-radius: 8rpx;
			background: rgba(0, 0, 0, 0.1);

			.image-del {
				position: absolute;
				top: 0;
				right: 0;
				width: 42rpx;
				height: 42rpx;
				background: rgba(0, 0, 0, 0.5);
				border-radius: 0 8rpx 0 8rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				z-index: 1;
			}

			image {
				width: 100%;
				height: 100%;
			}
		}
	}

	:deep(.uv-form-item__body),
	.tips-box {
		padding: 30rpx;
	}
	.btn-box {
		position: sticky;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 30rpx;
		background-color: #fff;
		border: 1px solid #f5f5f5;
		margin-top: 20rpx;
		z-index: 9;
	}
</style>